<?php

namespace App\Modules\Common;


use App\Library\Rank\AbstractSingleRank;
use App\Modules\Rebate\Models\Rebate;
use App\Modules\User\Models\User;
use Carbon\Carbon;
use Illuminate\Support\Facades\Redis;

class LowerRebateRank extends AbstractSingleRank
{
    protected static $key = "lower:rebate";

    public static function setKey($prefix)
    {
        self::$key = "lower:rebate:{$prefix}";
    }

    public static function flush()
    {
        $keys = Redis::keys("lower:rebate*");
        if (!is_null($keys)) {
            foreach ($keys as $value) {
                Redis::del(mb_substr($value, 10));
            }
        }
    }

    public static function refresh()
    {
        static::flush();
        self::multi(function () {
            User::query()
                ->where('level', 3)
                ->orderBy('id', 'desc')
                ->each(function ($item) {
                    $user = $item->getTeam();
                    self::setKey("quarterly:".$item->id);
                    $rebates = Rebate::query()
                        ->where('created_at', '>', now()->startOfQuarter()->toDateTimeString())
                        ->where('level', 2)
                        ->whereIn('user_id', $user->pluck('id')->all())
                        ->selectRaw('user_id, sum(money) as money')
                        ->groupBy('user_id')
                        ->get()
                        ->keyBy('user_id');
                    $user->each(function ($item2) use ($rebates) {
                        $rebate = $rebates->get($item2->id);
                        self::update($item2->id, $rebate->money??0);
                    });
                    self::setKey("annual:".$item->id);
                    $rebates = Rebate::query()
                        ->where('created_at', '>', now()->startOfYear()->toDateTimeString())
                        ->whereIn('user_id', $user->pluck('id')->all())
                        ->where('level', 2)
                        ->selectRaw('user_id, sum(money) as money')
                        ->groupBy('user_id')
                        ->get()
                        ->keyBy('user_id');
                    $user->each(function ($item2) use ($rebates) {
                        $rebate = $rebates->get($item2->id);
                        self::update($item2->id, $rebate->money??0);
                    });
                });
        });
    }
}
